<template>
  <div v-loading="loading" element-loading-text="模型生成中...">
    <div style="width: 280px; height: 400px; border: 1px solid white; ">
      <el-form ref="form" label-width="90px">
        <el-radio-group v-model="type" size="small" @input="changeType">
          <el-radio-button label="1">三角形</el-radio-button>
          <el-radio-button label="2">矩形</el-radio-button>
          <el-radio-button label="3">锯齿形</el-radio-button>
          <el-radio-button label="4">梯形</el-radio-button>
        </el-radio-group>
        <el-form-item label="螺距">
          <el-input size="small" onkeypress="return event.charCode >= 48 && event.charCode <= 57" v-model.number="p" type="number" placeholder="请输入内容">
            <i slot="suffix" style="font-style:normal; color: #606266;">mm</i>
          </el-input>
        </el-form-item>
        <el-form-item label="螺纹大径">
          <el-input size="small" onkeypress="return event.charCode >= 48 && event.charCode <= 57" v-model.number="d" type="number" placeholder="请输入内容">
            <i slot="suffix" style="font-style:normal; color: #606266;">mm</i>
          </el-input>
        </el-form-item>
        <el-form-item label="长度">
          <el-input size="small" onkeypress="return event.charCode >= 48 && event.charCode <= 57" v-model.number="l" type="number" placeholder="请输入内容">
            <i slot="suffix" style="font-style:normal; color: #606266;">mm</i>
          </el-input>
        </el-form-item>
      </el-form>
      <div>
        <img src="/image/triangle.png"  height="225" style="margin-top: 3px" width="280" v-show="type==='4'"/>
        <img src="/image/rectangle.png" height="228" width="280"v-show="type==='2'"/>
        <img src="/image/zigza.png" height="209" style="margin-top: 19px" width="280"v-show="type==='3'"/>
        <img src="/image/trapezoid.png" height="172" style="margin-top: 56px" width="280"v-show="type==='1'"/>
        <div style="margin-top: 10px;text-align: center;">
          <el-button type="primary" size="small" @click="creatThreadedRod">确定</el-button>
          <el-button size="small"  @click="closeDialog">取消</el-button>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
  import {
    Axis,
    CrownCADPlugin,
    Direction, PluginCADToolFunctionType,
    PluginFunctionType,
    Point
  } from "../../../../nodeApp/static/lib/crowncad-plugin-sdk-0.0.1";
  export default {
    name: "ThreadedRod",
    data() {
      return {
        loading: false,
        type: '1',
        p: 2,   // 螺距
        d: 12,  // 螺纹大径
        l: 30,   // 螺纹杆长
        H: 0,  // 三角形高度
        d1: 0, // 螺纹小径
        d2: 0, // 螺纹中经
        d3:0, // 内螺纹小径
        w: 0, // 中经处齿宽(牙宽)
        h1: 0, //牙高
        Ac: 0, // 间隙
        R1: 0, // 牙顶圆角
        R2: 0, // 牙底圆角
        h3: 0, // 外螺纹牙高
        L1: 0, // 基本底宽
        R:0 // 倒角半径

      }
    },
    mounted() {
      //创建插件对象
      this.crownCADPlugin = new CrownCADPlugin();
      //设置CrownCAD平台地址
      this.crownCADPlugin.setParentOrigin(window.url);
      //.设置与CrownCAD平台尝试建立连接的次数
      this.crownCADPlugin.setMaxAttempt(5);
      //设置插件在CrownCAD平台显示的尺寸
      this.crownCADPlugin.setLayout(300, 300, 480);

      //.发送与CrownCAD平台建立连接的请求
      this.crownCADPlugin.connect().then(() => {
        this.crownCADPlugin.request.execFunction(PluginFunctionType.LAYOUT, { minWidth: 300, width: 300, maxHeight: 435})
        console.log("connected!");
      });
    },
    methods: {
      //关闭对话框
      closeDialog() {
        this.crownCADPlugin.request.execFunction(PluginCADToolFunctionType.CLOSEACTIVECMD, null);
      },

      changeType(e) {

      },
      // 准备大径小径等画草图数据
      updateData() {

        // 根据不同的齿形，更新计算相关参数
        switch (this.type) {
          case '1':   // 三角形
            this.H = Math.sqrt(3)/2 * this.p;
            this.d1 = this.d - 2*5/8 * this.H;
            this.d2 = this.d - 2*3/8 * this.H;
            this.w = this.p/2;
            break;
          case '2': // 矩形
            this.h1 = this.p/2;
            this.w = this.p/2;
            break;
          case '3': // 锯齿形
            this.h1= 0.75*this.p
            this.d2= this.d- this.h1
            this.d3= this.d- 1.735534* this.p
            this.R=0.124271* this.p

            break;
          case '4': // 梯形
            if(this.p===1.5) this.Ac= 0.15
            if(this.p>=2 && this.p<= 5) this.Ac= 0.25
            if(this.p>=6 && this.p<= 12) this.Ac= 0.25
            if(this.p>=14 && this.p<= 44) this.Ac= 1

            this.R1= 0.5* this.Ac
            this.R2= this.Ac
            this.h3= 0.5* this.p + this.Ac
            this.L1= 0.366* this.p


            break;

          default:

            break;
        }



      },

      // 开始画图方法
      async creatThreadedRod() {
        this.loading = true
        // 更新数据
        this.updateData()
        //清空command
        this.crownCADPlugin.command.clearCommand();
        //创建草图，命名为草图1
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图1', datumId: 8});

        //绘制螺纹杆
        this.crownCADPlugin.command.sketch.createCircle({
          centerPoint: new Point(0, 0, 0),
          circlePoint: new Point(0, 0.5 * this.d, 0),
        })

        //退出草图
        this.crownCADPlugin.command.sketch.exitSketch();
        //实现草图操作，参数true会覆盖之前的草图，不传则不会
        await this.crownCADPlugin.command.execute(true)

        // await this.createExtrude()

        // 根据齿形绘制不同的齿形
        switch (this.type) {
          case '1':
            //绘制三角形齿形
            await this.createTriangle()
            break;
          case '2':
            //绘制矩形齿形
            await this.createRectangle()
            break;
          case '3':
            //绘制锯齿形
            await this.createZigzag()
            break;
          case '4':
            //绘制梯形齿形
            await this.createTrapezoid()
            break;
          default:
            break;
        }

        // await this.createExtrude()

        // 绘制螺旋线
        await this.createHelixCurve()
        // 拉伸螺纹杆
        await this.createExtrude()
        //齿形依据螺旋曲线进行扫描切除
        await this.sweepCut()
      },
      // 拉伸螺纹杆
      async createExtrude() {
        this.crownCADPlugin.command.clearCommand();
        // 获取草图1的featuresid
        let res= await this.crownCADPlugin.query.getFeaturesByNames(['草图1'])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图1"]})
        // 获取草图1的entityid
        let res1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
        // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
        // 拉伸草图1的圆
        this.crownCADPlugin.command.solid.extrude({
          sketch: res1.data.entities[0]?.id,
          height1: this.l,
          // extrudeType1: 4
        }, "拉伸凸台");
        await this.crownCADPlugin.command.execute()
      },

      //绘制三角形齿形
      async createTriangle() {

        // let midx= this.d* 0.5* Math.tan(30/180 * Math.PI)
        // let midL= this.d1* 0.5* Math.tan(30/180 * Math.PI)
        // let midLx= midx - midL
        // let midRx= midx + midL
        // let bottomRx= 2* midx
        let p= (this.d2* 0.5- this.d1* 0.5)/(this.d* 0.5- this.d1* 0.5)
        let Lc= (this.d* 0.5- this.d1* 0.5)/ Math.sin(60/180 * Math.PI)
        let midL= Lc* p*p/(1-p*p)
        let midLx= (this.d* 0.5- this.d1* 0.5)* Math.tan(30/180 * Math.PI)
        let topLx= (this.p* 0.95 - midL- Lc)/ 2
        let topLy= topLx/Math.tan(30/180 * Math.PI)

        this.crownCADPlugin.command.clearCommand();
        //绘制梯形的草图2
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图2', datumId: 22});
        //绘制梯形的4条边
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(midLx, this.d1*0.5,0),
          endPoint:new Point(-1* topLx, this.d*0.5 + topLy,0),
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(-1* topLx, this.d*0.5 + topLy,0),
          endPoint:new Point( (this.p* 0.95 - midL- Lc)/ 2 + midL+ Lc, this.d*0.5+ topLy,0)
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point((this.p* 0.95 - midL- Lc)/ 2 + midL+ Lc, this.d*0.5+ topLy,0),
          endPoint:new Point(midLx+ midL, this.d1*0.5,0)
        })

        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(midLx, this.d1*0.5,0),
          endPoint: new Point(midLx+ midL, this.d1*0.5,0)
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

      },

      //绘制矩形齿形
      async createRectangle() {

        this.crownCADPlugin.command.clearCommand();
        //绘制梯形的草图2
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图2', datumId: 22});
        //绘制4条边
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(0, this.d*0.5- this.w,0),
          endPoint:new Point(0, this.d*0.5 + 0.5,0),
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(0, this.d*0.5 + 0.5,0),
          endPoint:new Point(this.w, this.d*0.5 + 0.5,0)
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(this.w, this.d*0.5 + 0.5,0),
          endPoint:new Point(this.w, this.d*0.5- this.w,0)
        })

        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(this.w, this.d*0.5- this.w,0),
          endPoint: new Point(0, this.d*0.5- this.w,0)
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

      },

      //绘制锯齿形
      async createZigzag() {

        let h= this.d2*0.5 -this.d3*0.5
        let Lx= h* Math.tan(3/180 * Math.PI)
        let b= (0.5* this.p- h/ Math.tan(60/180 * Math.PI)- Lx)/(Math.tan(3/180 * Math.PI)+ Math.tan(30/180 * Math.PI))
        let bottomRx= (this.d*0.5 -this.d3*0.5)* Math.tan(3/180 * Math.PI)+ 0.5* this.p- h/ Math.tan(60/180 * Math.PI)- Lx

        let y= (this.p*0.95- (bottomRx+ (this.d*0.5 -this.d3*0.5)/ Math.tan(60/180 * Math.PI)))/(Math.tan(3/180 * Math.PI)+ Math.tan(30/180 * Math.PI))

        this.crownCADPlugin.command.clearCommand();
        //绘制梯形的草图2
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图2', datumId: 22});
        //绘制4条边
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point( (this.d*0.5 -this.d3*0.5)* Math.tan(3/180 * Math.PI), this.d3*0.5,0),
          endPoint:new Point(-1* y* Math.tan(3/180 * Math.PI) , this.d*0.5 + y,0),
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(-1* y* Math.tan(3/180 * Math.PI) , this.d*0.5 + y,0),
          endPoint:new Point(this.p*0.95-y* Math.tan(3/180 * Math.PI) , this.d*0.5 + y,0)
        })

        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(this.p*0.95-y* Math.tan(3/180 * Math.PI) , this.d*0.5 + y,0),
          endPoint:new Point(bottomRx, this.d3*0.5,0)
        })

        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(bottomRx, this.d3*0.5,0),
          endPoint: new Point((this.d*0.5 -this.d3*0.5)* Math.tan(3/180 * Math.PI), this.d3*0.5,0)
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

        await this.getZigzagInfo()
      },


      //绘制梯形齿形
      async createTrapezoid() {

        let bottomLx= this.h3 * Math.tan(15/180 * Math.PI)
        let bottomLy= this.d* 0.5 - this.h3
        let bottomLen= this.L1*0.5- this.Ac* Math.tan(15/180 * Math.PI)*2
        let topLx= (0.95*this.p- (bottomLen + 2* bottomLx))* 0.5* -1

        let topLy=topLx/ Math.tan(15/180 * Math.PI)*-1 + this.d* 0.5


        this.crownCADPlugin.command.clearCommand();
        //绘制梯形的草图2
        this.crownCADPlugin.command.sketch.createSketch({sketchName: '草图2', datumId: 22});
        //绘制4条边
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(bottomLx, bottomLy,0),
          endPoint:new Point(topLx, topLy,0),
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(topLx, topLy,0),
          endPoint:new Point(0.95*this.p+ topLx, topLy,0)
        })
        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(0.95*this.p+ topLx, topLy,0),
          endPoint:new Point(bottomLx+ bottomLen, bottomLy,0)
        })

        this.crownCADPlugin.command.sketch.createSketchLine({
          startPoint: new Point(bottomLx+ bottomLen, bottomLy,0),
          endPoint: new Point(bottomLx, bottomLy,0)
        })

        this.crownCADPlugin.command.sketch.exitSketch();
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

      },


      // 获取锯齿形草图的信息
      async getZigzagInfo() {
        let res= await this.crownCADPlugin.query.getFeaturesByNames(['草图2'])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图1"]})
        // 获取草图1的entityid
        let result= await this.crownCADPlugin.query.getElementsByFeatureId(res.data.features[0]?.id)
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图2"]})
        // let result=await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETElEMENTSBYFEATURE, {featureId: res.features[0]?.id})
        let rlElements= []
        let bottomEl=[]
        let left= null // 左边
        let right = null // 右边
        let bottom= null //下边
        let top= null // 上边
        // 找到两条斜边和水平边
        result.data.elements.forEach(element => {
          if(element.type===8 && element.params.type=== 10 && element.params.startPoint['1']!== element.params.endPoint['1']) {
            rlElements.push(element)
          }
          if(element.type===8 && element.params.type=== 10 &&element.params.startPoint['1']=== element.params.endPoint['1']){
            bottomEl.push(element)
          }
        })

        if(rlElements[0].params.middlePoint['2']> rlElements[1].params.middlePoint['2']) {
          left= rlElements[0]
          right= rlElements[1]
        } else {
          left= rlElements[1]
          right= rlElements[0]
        }

        if(bottomEl[0].params.startPoint['1']> bottomEl[1].params.startPoint['1']) {
          top= bottomEl[0]
          bottom= bottomEl[1]
        } else {
          top= bottomEl[1]
          bottom= bottomEl[0]
        }

        // 绘制两条边的圆角
        await this.createFilletCurve(left, right, bottom)

      },

     // 绘制两条边的圆角
      async createFilletCurve(left, right, bottom) {

        this.crownCADPlugin.command.clearCommand();
        this.crownCADPlugin.command.sketch.editSketch({sketchName: '草图2'});

        // this.crownCADPlugin.command.sketch.createCircle({
        //   centerPoint: new Point(0, 0, 0),
        //   circlePoint: new Point(0, 20, 0),
        // })
        // 绘制两条边的圆角
        this.crownCADPlugin.command.sketch.createFilletCurve({
          curveId1: left.id,
          curveId2: right.id,
          radius: this.R, })

        // 删除下边
        this.crownCADPlugin.command.sketch.deleteElements({
          elementIds: [bottom.id],
        })
        this.crownCADPlugin.command.sketch.exitEditSketch({sketchName: '草图2'});
        await this.crownCADPlugin.command.execute()
        this.crownCADPlugin.command.clearCommand();

      },

      //绘制螺旋线
      async createHelixCurve() {
        //获取草图4信息
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图1"]})
        let res= await this.crownCADPlugin.query.getFeaturesByNames(['草图1'])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图1"]})
        // 获取草图1的entityid

        if (res?.data.features) {
          let res1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
          //获取草图entitiesid
          // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})

          if (res1?.data.entities) {

            //穿件螺旋曲线
            this.crownCADPlugin.command.curve.createHelixCurve({
              helixPlane: res1.data.entities[0]?.id,
              inputModel: 0,
              step: this.p,
              height: parseInt(this.l) + 10,
              rotation: 0,
              isInvert: 0,
              startAngle: 90
            },'螺旋曲线')


            await this.crownCADPlugin.command.execute()

          }

        }
      },

      //齿形依据螺旋曲线进行扫描切除
      async sweepCut() {
        this.crownCADPlugin.command.clearCommand();
        //获取草图0的信息
        let res= await this.crownCADPlugin.query.getFeaturesByNames(['草图2'])
        // let res= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["草图2"]})
        if (res?.data.features) {
          //获取草图0元素信息
          let res1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([res.data.features[0]?.id])
          // let res1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [res.features[0]?.id]})
          //获取旋转切除1实体的信息
          let ferRes= await this.crownCADPlugin.query.getFeaturesByNames(['拉伸凸台'])
          // let ferRes= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["拉伸凸台"]})
          //获取旋转切除1实体的entitiyid
          let ferRes1= await this.crownCADPlugin.query.getEntitiesByFeatureIds([ferRes.data.features[0]?.id])
          // let ferRes1= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [ferRes.features[0]?.id]})
          //获取螺旋曲线的信息
          let ferRes2= await this.crownCADPlugin.query.getFeaturesByNames(['螺旋曲线'])
          // let ferRes2= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETFEATURESBYNAMES, {featureNames: ["螺旋曲线"]})
          //获取螺旋曲线的entitiyid
          let ferRes3= await this.crownCADPlugin.query.getEntitiesByFeatureIds([ferRes2.data.features[0]?.id])
          // let ferRes3= await this.crownCADPlugin.request.execFunction(PluginFunctionType.GETENTITIESBYFEATUREIDS, {featureIds: [ferRes2.features[0]?.id]})
          //齿形依据螺旋曲线进行扫描切除
          this.crownCADPlugin.command.solid.sweepCut({
            sweepType: 0,
            sweepProfile:res1.data.entities[0]?.id,
            sweepPath:[ferRes3.data.entities[0]?.id],
            sweepDirection: 0,
            profileDirection:2,
            cutSolids: [ferRes1.data.entities[0]?.id]
          }, "扫描切除");


          await this.crownCADPlugin.command.execute()
          this.crownCADPlugin.command.clearCommand();
          await this.setEntityVisible([ferRes3.data.entities[0]?.id])
          this.loading= false
        }
      },

      async setEntityVisible(entityIds) {
        this.crownCADPlugin.command.clearCommand();
        this.crownCADPlugin.command.common.setEntityVisible({
          entityIds, visibleType: 0, })
        await this.crownCADPlugin.command.execute();
      },
    }
  }
</script>

<style scoped>
  >>> .el-form-item {
    margin-bottom: 0!important;
  }
  >>> .el-form-item__label {
    margin-bottom: 0!important;
  }
</style>
